import axios from "axios";
import {useTokenStore} from "@/stores/token.js";
import {useUserStore} from "@/stores/User.js";
//创建aixos的对象
const service=axios.create({
    baseURL:import.meta.env.VITE_SERVER_ADDR
});
//请求拦截器
service.interceptors.request.use(req =>{
  const tokenStore=useTokenStore();
    if(tokenStore.tokenStr){
        req.headers.token=tokenStore.tokenStr;
    }
    return req;

},error=>{

});
service.interceptors.response.use(resp =>{
  const token =resp.headers.token;
  if(token){
      const tokenStore=useTokenStore();
      tokenStore.update(token);
  }
  return resp.data
},error => {
        if (error.status == 403) {
            ElMessage.error({
                message: '令牌错误，请重新登录',
                duration: 1200,
                onClose: () => {
                    //提示信息消失的回调
                    //删除sessionStorage中的token,user
                    const tokenStore=useTokenStore();
                    tokenStore.$reset();
                    const  userStr=useUserStore();
                    userStr.$reset();
                    //跳转到登录页
                    let currentpath=router.currentRoute.value.path;
                    if (currentpath.startsWith("/admin")){
                        router.push('/admin/login');
                    }else {
                        router.push('/user/login');
                    }
                }
            });
        }
});

export default service;
